package com.learning.springmvc.base.controllers.controller;

import com.learning.springmvc.base.controllers.bean.User;
import com.learning.springmvc.base.controllers.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Objects;

/**
 * ClassName: UserSessionController
 * Description:
 * Date: 2019/5/15 9:24 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Controller
@RequestMapping("user/session")
@SessionAttributes("user")
public class UserSessionController {

    @Autowired
    private UserService userService;

    /**
     * http://localhost:8080/user/session/get?name=sam
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/get")
    public String get(User user, Model model) {
        user = userService.get(user.getName());

        // 一般默认是request请求域的
        // @SessionAttributes 则会把这个数据放入session请求域
        model.addAttribute("user", user);

        return "user";
    }


    /**
     * http://localhost:8080/user/session/return
     * <p>
     * 在多个请求之间共用某个模型属性数据，使用注解 @SessionAttributes。spring mvc 会将模型中对应的属性暂存到 HttpSession 中
     *
     * @param modelMap
     * @param sessionStatus
     * @return
     */
    @RequestMapping(value = "/return")
    public String get(ModelMap modelMap, SessionStatus sessionStatus) {

        // 读取模型中的数据
        User user = (User) modelMap.get("user");
        if (Objects.nonNull(user)) {
            user.setName("Rabbi");

            // 清除本处理器对应的会话属性
            sessionStatus.setComplete();
        }
        return "user";
    }

}
